"""
服务定位器，用于管理服务实例和依赖
"""
from typing import Dict, Type, TypeVar, Any, Optional
from app.state.app_state_manager import AppStateManager

T = TypeVar('T')


class ServiceLocator:
    """
    服务定位器，用于管理服务实例和依赖
    """
    _instance = None
    _services: Dict[str, Any] = {}
    
    def __new__(cls):
        """
        单例模式实现
        """
        if cls._instance is None:
            cls._instance = super(ServiceLocator, cls).__new__(cls)
        return cls._instance
    
    @classmethod
    def register(cls, service_type: Type[T], instance: T) -> None:
        """
        注册服务实例
        
        @param service_type: 服务类型
        @param instance: 服务实例
        """
        cls._services[service_type.__name__] = instance
    
    @classmethod
    def get(cls, service_type: Type[T]) -> Optional[T]:
        """
        获取服务实例
        
        @param service_type: 服务类型
        @return: 服务实例，如果不存在则返回 None
        """
        return cls._services.get(service_type.__name__)
    
    @classmethod
    def clear(cls) -> None:
        """
        清除所有服务实例
        """
        cls._services.clear()

    @staticmethod
    def initialize():
        """初始化服务定位器，注册基础服务"""
        # 创建并注册AppStateManager
        state_manager = AppStateManager()
        ServiceLocator.register(AppStateManager, state_manager)
        
        # 记录日志
        logger = Logger.get_logger("service_locator")
        logger.info("服务定位器已初始化，注册了AppStateManager状态管理器") 